<template>
  <div class="edit-profile" v-if="visible"
    :class="{ 'slide-in': visible, 'slide-out': isSlidingOut, 'dark-mode': isDarkMode }">
    <div class="edit-profile-header">
      <van-icon name="arrow-left" class="close-edit-profile" @click="hideEditProfile" />
      <div class="edit-profile-title">编辑资料</div>
      <i></i>
    </div>
    <div class="basic-information">基本资料</div>
    <ul class="edit-profile-list">
      <li class="edit-avatar" @click="selectAvatar">
        <span>头像</span>
        <div class="avatar-img" :style="{ backgroundImage: `url(${userAvatar})` }"></div>
      </li>
      <li class="nickname" @click="showChangeName">
        <div>昵称 <span class="name">{{ userName }}</span></div>
        <van-icon name="arrow" class="arrow-icon" />
      </li>
    </ul>
    <div class="divider"></div>
    <div class="dark-mode-section">
      <div class="dark-mode-item" @click="toggleDarkMode">
        <span>夜间模式</span>
        <van-switch v-model="isDarkMode" size="20px" @click.stop />
      </div>
    </div>
    <div class="logout-section">
      <div class="logout-btn" @click="handleLogout">
        <span>退出登录</span>
      </div>
    </div>

    <input type="file" ref="avatarInput" style="display: none" accept="image/*" @change="handleAvatarSelect" />

    <van-dialog v-model:show="isChangeName" title="修改昵称" show-cancel-button @confirm="changeName">
      <input type="text" v-model="tempNickname" placeholder="请输入昵称" class="cName-input" />
    </van-dialog>

    <van-dialog v-model:show="showLogoutDialog" title="确认退出" message="确定要退出登录吗？" show-cancel-button
      @confirm="confirmLogout" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { showToast } from 'vant';
import { useWatchHistoryStore } from '@/stores/watchHistory';
import { useDarkModeStore } from '@/stores/darkMode';
import defaultAvatar from '@/assets/img/my/user-avatar.jpg';

const emit = defineEmits(['update']);

// 观看记录 store
const watchHistoryStore = useWatchHistoryStore();

// 夜间模式 store
const darkModeStore = useDarkModeStore();
const isDarkMode = computed({
  get: () => darkModeStore.isDarkMode,
  set: (value) => darkModeStore.setDarkMode(value)
});

// 显示状态
const visible = ref(false);
const isSlidingOut = ref(false);
const isChangeName = ref(false);
const showLogoutDialog = ref(false);
const avatarInput = ref<HTMLInputElement | null>(null);

// 用户资料（初始化为默认值）
const userAvatar = ref(defaultAvatar);
const userName = ref('');
const tempNickname = ref('');

// 编辑资料时的初始值（用于检测是否有修改）
const initialEditData = ref({
  nickname: '',
  avatar: '',
});

// 获取默认昵称（用户+手机号后四位）
const getDefaultNickname = (phoneNumber: string) => {
  const lastFour = phoneNumber.slice(-4);
  return `用户${lastFour}`;
};

// 加载用户数据
const loadUserData = () => {
  const currentPhone = localStorage.getItem('currentPhoneNumber');
  if (!currentPhone) return;

  const users = JSON.parse(localStorage.getItem('users') || '[]');
  const user = users.find((u: any) => u.phoneNumber === currentPhone);

  if (user) {
    // 如果有昵称，使用存储的昵称，否则使用默认昵称
    userName.value = user.nickname || getDefaultNickname(currentPhone);

    // 如果有头像，使用存储的头像，否则使用默认头像
    if (user.avatar) {
      userAvatar.value = user.avatar;
    } else {
      userAvatar.value = defaultAvatar;
    }
  } else {
    // 如果没有找到用户，使用默认值
    userName.value = getDefaultNickname(currentPhone);
    userAvatar.value = defaultAvatar;
  }
};

// 显示编辑资料模块
const show = () => {
  loadUserData();
  // 保存当前的初始值，用于后续比较
  initialEditData.value = {
    nickname: userName.value,
    avatar: userAvatar.value,
  };
  visible.value = true;
  isSlidingOut.value = false;
};

// 隐藏编辑资料模块
const hideEditProfile = () => {
  // 在关闭前保存修改的数据
  saveEditDataIfChanged();

  isSlidingOut.value = true;
  // 等待动画完成后隐藏元素
  setTimeout(() => {
    visible.value = false;
    isSlidingOut.value = false;
    emit('update');
  }, 300);
};

// 检测并保存编辑的数据（只有与默认值不同时才保存）
const saveEditDataIfChanged = () => {
  const currentPhone = localStorage.getItem('currentPhoneNumber');
  if (!currentPhone) return;

  const defaultNickname = getDefaultNickname(currentPhone);
  const users = JSON.parse(localStorage.getItem('users') || '[]');
  const userIndex = users.findIndex((u: any) => u.phoneNumber === currentPhone);

  if (userIndex === -1) return;

  // 检测昵称：如果与初始值不同，才进行保存或删除操作
  if (userName.value !== initialEditData.value.nickname) {
    if (userName.value !== defaultNickname) {
      // 当前值不等于默认值，保存
      users[userIndex].nickname = userName.value;
    } else {
      // 当前值等于默认值，删除存储的昵称
      if (users[userIndex].nickname) {
        delete users[userIndex].nickname;
      }
    }
  }

  // 检测头像：如果与初始值不同，才进行保存或删除操作
  if (userAvatar.value !== initialEditData.value.avatar) {
    if (userAvatar.value !== defaultAvatar) {
      // 当前值不等于默认值，保存
      users[userIndex].avatar = userAvatar.value;
    } else {
      // 当前值等于默认值，删除存储的头像
      if (users[userIndex].avatar) {
        delete users[userIndex].avatar;
      }
    }
  }

  // 保存更新后的users数组
  localStorage.setItem('users', JSON.stringify(users));
};

// 显示修改昵称弹窗
const showChangeName = () => {
  tempNickname.value = userName.value;
  isChangeName.value = true;
};

// 修改昵称
const changeName = () => {
  if (tempNickname.value.trim() !== '') {
    userName.value = tempNickname.value.trim();
    isChangeName.value = false;
  } else {
    showToast('昵称不能为空');
  }
};

// 选择头像
const selectAvatar = () => {
  avatarInput.value?.click();
};

// 处理头像选择
const handleAvatarSelect = (e: Event) => {
  const target = e.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    readFileAsDataURL(file, (result) => {
      userAvatar.value = result;
      // 不立即保存，等关闭编辑资料模块时统一检测保存
    });
  }
  // 重置input值，以便可以重复选择同一文件
  target.value = '';
};

// 通用方法：读取文件为DataURL
const readFileAsDataURL = (file: File, callback: (result: string) => void) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    callback(e.target?.result as string);
  };
  reader.readAsDataURL(file);
};

// 切换夜间模式
const toggleDarkMode = () => {
  darkModeStore.toggleDarkMode();
};

// 处理退出登录
const handleLogout = () => {
  showLogoutDialog.value = true;
};

// 确认退出登录
const confirmLogout = () => {
  localStorage.setItem('isLoggedIn', 'false');
  localStorage.removeItem('currentPhoneNumber');
  // 清除观看记录
  watchHistoryStore.clearHistory();
  showLogoutDialog.value = false;
  showToast('已退出登录');
  // 关闭编辑资料模块
  hideEditProfile();
  // 触发登录状态更新事件
  window.dispatchEvent(new Event('loginSuccess'));
};

// 暴露方法供外部调用
defineExpose({
  show,
  hide: hideEditProfile,
});
</script>

<style scoped lang="less">
.edit-profile {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  transform: translateX(100%);
  transition: transform 0.3s ease, background-color 0.3s ease, color 0.3s ease;

  &.dark-mode {
    background-color: #000;
    color: #fff;
  }

  &.slide-in {
    transform: translateX(0);
    transition: transform 0.3s ease;
  }

  &.slide-out {
    transform: translateX(100%);
    transition: transform 0.3s ease;
  }

  .edit-profile-header {
    width: 100%;
    height: 6vh;
    padding: 0 3vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .close-edit-profile {
      color: #aaa;
      font-size: 14px;
      cursor: pointer;
    }

    .edit-profile-title {
      font-size: 14px;
      font-weight: 350;
    }

    i {
      width: 14px;
    }
  }

  .basic-information {
    height: 5vh;
    padding: 0 3vw;
    box-sizing: border-box;
    background-color: #f8f8f8;
    color: #333;
    display: flex;
    align-items: center;
    font-size: 12px;
    font-weight: 350;
    transition: background-color 0.3s ease, color 0.3s ease;
  }

  .edit-profile-list {
    width: 100%;
    padding: 0 3vw;
    margin-top: 2vh;
    box-sizing: border-box;

    li {
      width: 100%;
      height: 6vh;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;
      font-weight: 350;
      cursor: pointer;

      &:not(:last-child) {
        border-bottom: 1px solid #eeeded;
      }

      span {
        color: #333;
      }
    }

    .edit-avatar {
      .avatar-img {
        background-size: cover;
        background-repeat: no-repeat;
        background-position: center;
        height: 80%;
        aspect-ratio: 1/1;
        border-radius: 50%;
      }
    }

    .nickname {
      .name {
        margin-left: 3vw;
        color: #999;
      }

      .arrow-icon {
        font-size: 12px;
        color: #ccc;
      }
    }

  }

  .divider {
    width: 100%;
    height: 1px;
    background-color: #eeeded;
    margin: 2vh 0;
  }

  .dark-mode-section {
    width: 100%;
    padding: 0 3vw;
    box-sizing: border-box;

    .dark-mode-item {
      width: 100%;
      height: 6vh;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;
      font-weight: 350;
      cursor: pointer;

      span {
        color: #333;
      }
    }
  }

  .logout-section {
    width: 100%;
    padding: 2vh 3vw;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;

    .logout-btn {
      width: 100%;
      height: 6vh;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: 350;
      cursor: pointer;
      border-radius: 4px;
      background-color: #f5f5f5;
      transition: background-color 0.2s;

      &:active {
        background-color: #e8e8e8;
      }

      span {
        color: #ff4757;
      }
    }
  }

  &.dark-mode {
    .edit-profile-header {
      .close-edit-profile {
        color: #ccc;
      }

      .edit-profile-title {
        color: #fff;
      }
    }

    .basic-information {
      background-color: #1a1a1a;
      color: #fff;
    }

    .edit-profile-list {
      li {
        span {
          color: #fff;
        }

        &:not(:last-child) {
          border-bottom-color: #333;
        }
      }

      .nickname {
        .name {
          color: #999;
        }

        .arrow-icon {
          color: #666;
        }
      }
    }

    .divider {
      background-color: #333;
    }

    .dark-mode-section {
      .dark-mode-item {
        span {
          color: #fff;
        }
      }
    }

    .logout-section {
      .logout-btn {
        background-color: #333;

        &:active {
          background-color: #444;
        }

        span {
          color: #ff4757;
        }
      }
    }
  }
}

:deep(.cName-input) {
  width: 100%;
  padding: 1vh 3vw;
  margin-bottom: 2vh;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
  outline: none;
}
</style>
